package com.oreilly.ez.service.impl;

import com.oreilly.ez.entity.EzDetail;
import com.oreilly.ez.entity.EzIndex;
import com.oreilly.ez.repo.EzDetailRepo;
import com.oreilly.ez.repo.EzIndexRepo;
import com.oreilly.ez.service.EzIndexService;
import com.oreilly.ez.util.CloneUtils;
import com.oreilly.ez.vo.EzDetailVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class EzIndexServiceImpl  implements EzIndexService{


    @Autowired
    private EzIndexRepo ezIndexRepo;


    @Autowired
    private EzDetailRepo detailRepo;

    @Override
    public EzIndex save(EzIndex item) {

        // is update ??
        Integer sid = item.getSid();
        if(sid != null){
            EzIndex dbItem = ezIndexRepo.getOne(sid);

            CloneUtils.copyProperties(item, dbItem);
            CloneUtils.copyProperties(dbItem, item);

        }

        return ezIndexRepo.save(item);

    }

    @Override
    public void remove(Integer sid) {

        ezIndexRepo.deleteById(sid);
    }


    @Override
    public Page<EzIndex> find(EzIndex item, Pageable pageable) {


        return ezIndexRepo.findAll(pageable);
    }

    @Override
    public List<EzIndex> findByCate(Integer cateSid) {
        List<EzIndex> indexList = ezIndexRepo.findByCate(cateSid);
        if(indexList.size() > 0){

            for (EzIndex index : indexList) {

                List<EzDetail> detailList = detailRepo.findByIndex(index);
                List<EzDetailVO> voList = detailList.stream().map(ezDetail -> {

                    EzDetailVO vo = new EzDetailVO();
                    vo.setSid(ezDetail.getSid());
                    vo.setSname(ezDetail.getSname());
                    return vo;
                }).collect(Collectors.toList());
                index.setDetailList(voList);
            }
        }
        return indexList;
    }

    @Override
    public EzIndex findOne(Integer sid) {

        return ezIndexRepo.findById(sid).get();
    }


}
